<?php

namespace backend\modules\member\controllers;

use addons\TfFutures\common\models\Logs;
use addons\TfFutures\common\models\Member;
use common\helpers\ArrayHelper;
use common\models\common\Capital;
use common\models\sys\Manager;
use Yii;
use common\models\common\SearchModel;
use common\components\Curd;
use backend\controllers\BaseController;

/**
 * 会员管理
 * Class MemberController
 * @package backend\modules\member\controllers
 * @author  jianyan74 <1666545092@qq.com>
 */
class CapitalController extends BaseController
{
    use Curd;

    /**
     * @var \yii\db\ActiveRecord
     */
    public $modelClass = Capital::class;

    /*
     * 出金管理
     */
    public function actionOutManager()
    {
        $searchModel  = new SearchModel([
            'model'                  => $this->modelClass,
            'scenario'               => 'default',
            'relations'              => ['member' => ['username']],
            'partialMatchAttributes' => ['title'], // 模糊查询
            'defaultOrder'           => [
                'id' => SORT_DESC,
            ],
            'pageSize'               => $this->pageSize,
        ]);
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere([
            Capital::tableName() . '.status'      => 0,
            Capital::tableName() . '.order_group' => 'out',
        ]);
        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel'  => $searchModel,
        ]);
    }

    /*
     * 入金管理
     */
    public function actionInManager()
    {
        $searchModel  = new SearchModel([
            'model'                  => $this->modelClass,
            'scenario'               => 'default',
            'relations'              => ['member' => ['username']],
            'partialMatchAttributes' => [], // 模糊查询
            'defaultOrder'           => [
                'id' => SORT_DESC,
            ],
            'pageSize'               => $this->pageSize,
        ]);
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere([
            Capital::tableName() . '.status'      => 0,
            Capital::tableName() . '.order_group' => 'in',
        ]);
        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel'  => $searchModel,
        ]);
    }

    /**
     * 出金记录
     */
    public function actionOutLog()
    {
        $searchModel  = new SearchModel([
            'model'                  => $this->modelClass,
            'scenario'               => 'default',
            'relations'              => ['member' => ['username']],
            'partialMatchAttributes' => [], // 模糊查询
            'defaultOrder'           => [
                'updated_at' => SORT_DESC,
            ],
            'pageSize'               => $this->pageSize,
        ]);
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere([
            '<>',
            Capital::tableName() . '.status',
            0,
        ])
            ->andwhere([
                '=',
                Capital::tableName() . '.order_group',
                'out',
            ]);
        $daili = Manager::find()->select("rf_sys_manager.id,rf_sys_manager.username")->join('LEFT JOIN','rf_common_auth_assignment','rf_sys_manager.id=rf_common_auth_assignment.user_id')->where(["rf_common_auth_assignment.role_id"=>4,"rf_sys_manager.status"=>1])->asArray()->all();
        $daili = ArrayHelper::map($daili,"username","id");
        $id = Yii::$app->user->id;  //当前登录id
        if(!empty(in_array($id,$daili))) {
            //查询此代理下面的用户订单
            $member = \common\models\member\Member::find()->where(['daili'=>$id])->select('id,username')->asArray()->all();
            foreach ($member as $item){
                //获取到用户的id
                $member_id[] = $item['id'];
            }
            if(!empty($member_id)){
                $dataProvider->query->andFilterWhere(['in','member_id',$member_id]);
            } else {
                $dataProvider->query->andFilterWhere(['=','member_id',-1]);
            }
        }
        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel'  => $searchModel,
        ]);
    }

    /**
     * 入金记录
     */
    public function actionInLog()
    {
        $searchModel  = new SearchModel([
            'model'                  => $this->modelClass,
            'scenario'               => 'default',
            'relations'              => ['member' => ['username']],
            'partialMatchAttributes' => [], // 模糊查询
            'defaultOrder'           => [
                'updated_at' => SORT_DESC,
            ],
            'pageSize'               => $this->pageSize,
        ]);
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere([
            '<>',
            Capital::tableName() . '.status',
            0,
        ])
            ->andwhere([
                '=',
                Capital::tableName() . '.order_group',
                'in',
            ]);
        $daili = Manager::find()->select("rf_sys_manager.id,rf_sys_manager.username")->join('LEFT JOIN','rf_common_auth_assignment','rf_sys_manager.id=rf_common_auth_assignment.user_id')->where(["rf_common_auth_assignment.role_id"=>4,"rf_sys_manager.status"=>1])->asArray()->all();
        $daili = ArrayHelper::map($daili,"username","id");
        $id = Yii::$app->user->id;  //当前登录id
        if(!empty(in_array($id,$daili))) {
            //查询此代理下面的用户订单
            $member = \common\models\member\Member::find()->where(['daili'=>$id])->select('id,username')->asArray()->all();
            foreach ($member as $item){
                //获取到用户的id
                $member_id[] = $item['id'];
            }
            if(!empty($member_id)){
                $dataProvider->query->andFilterWhere(['in','member_id',$member_id]);
            } else {
                $dataProvider->query->andFilterWhere(['=','member_id',-1]);
            }
        }
        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel'  => $searchModel,
        ]);
    }


    /**
     * 入金
     * @param $id 信息id
     * @param $member_id  用户id
     * @param $status 状态
     * @return array
     */
//    public function actionPriceIn($id, $status, $member_id)
//    {
//        $capital = Capital::findOne($id);//入金信息
//        //用户资产
//        $member = Member::find()->where(['member_id'=>$member_id])->one();
//        if (empty($member)) {
//            throw new \Exception('用户不存在');
//        }
//
//        //信息状态
//        $capital = Capital::find()
//            ->where(['id' => $id, 'status' => '0'])
//            ->one();
//        if (empty($capital)) {
//            throw new \Exception('记录异常');
//        }
//
//        $old_price = $member->price; //原先余额
//        $price     = $capital->pay_fee;//充值金额
//
//        //1 通过 -1驳回
//        if($status == 1){
//            //更新用户资金
//            $member->price = bcadd($member->price, $capital->pay_fee, 2);
//            //将订单状态改为已完成
//            $capital->status = '1';
//            //日志备注
//            $desc = '用户充值，金额为：' . $price;
//
//            Logs::addLogs($member_id, '资金转入', $price, $old_price, $member->price, $desc);
//
//            return $member->save() && $capital->save()
//                ? $this->message('成功', $this->redirect('in-manager'), 'success')
//                : $this->message('失败', $this->redirect('in-manager'), 'error');
//        } else {
//            $capital->status = '-1';
//            $member          = Member::findOne($member_id);
//            $desc            = '资金转入驳回';
//            Logs::addLogs($member_id, '资金转入', $capital->pay_fee, $member->price, $member->price,
//                $desc);
//
//            return $capital->save()
//                ? $this->message('驳回成功', $this->redirect('in-manager'), 'success')
//                : $this->message('驳回失败', $this->redirect('in-manager'), 'error');
//        }
//    }

    /**
     * 出金
     * @param $id
     * @param $member_id
     * @param $status 状态
     * @return array
     */
    public function actionPriceOut($id, $status, $member_id)
    {
        $capital = Capital::findOne($id);//入金信息

        //用户资产
        $member = Member::find()->where(['member_id'=>$member_id])->one();
        if (empty($member)) {
            throw new \Exception('用户不存在');
        }

        //信息状态
        $capital = Capital::find()
            ->where(['id' => $id, 'status' => '0'])
            ->one();
        if (empty($capital)) {
            throw new \Exception('记录异常');
        }

        $old_price = $member->price; //原先余额
        $price     = $capital->pay_fee;//出金金额

        //1 正常  -1 驳回
        if($status == 1){
            $capital->status = '1';

            //日志备注
            $desc = '用户提现，金额为：' . $price;
            Logs::addLogs($member_id, '资金转入', $price, $old_price, $member->price, $desc);

            return $capital->save()
                ? $this->message('成功', $this->redirect('out-manager'), 'success')
                : $this->message('失败', $this->redirect('out-manager'), 'error');
        } else {
            //更新后资产
            $member    = Member::find()->where(['member_id'=>$member_id])->one();
            $new_price = bcadd($member->price, $capital->pay_fee,4);

            $desc = '资金转出驳回,用户返回金额' . $capital->pay_fee;
            Logs::addLogs($member_id, '资金转出', $capital->pay_fee, $member->price, $new_price,$desc);


            $capital->status = '-1';
            $member->price= $new_price;
            return $capital->save() && $member->save()
                ? $this->message('驳回成功', $this->redirect('out-manager'), 'success')
                : $this->message('驳回失败', $this->redirect('out-manager'), 'error');
        }
    }

}